<template>
  <a-form
    layout="inline"
    ref="formExpertRef"
    :colon="false"
    :model="formState"
    :labelCol="{ span: 10 }"
    :wrapperCol="{ span: 16 }"
  >
    <searchForm
      :num="Object.keys(formState).length"
      :needAdd="true"
      @addMethods="addMethods"
      @searchTable="searchTable(true)"
      @resetForm="resetForm"
      @getTableHeight="getTableHeight"
    >
      <template #search-title>
        <div style="display: inline-block">团队管理</div>
      </template>
      <template #form_1>
        <a-form-item label="团队名称" name="teamName">
          <a-input
            v-model:value="formState.teamName"
            placeholder="请输入"
            class="formWidth"
            allowClear
          />
        </a-form-item>
      </template>
      <template #form_2>
        <a-form-item label="所属企业" name="entName">
          <a-input
            v-model:value="formState.entName"
            placeholder="请输入"
            class="formWidth"
            allowClear
          />
        </a-form-item>
      </template>
      <template #form_3>
        <a-form-item label="所有者手机号" name="phone">
          <a-input
            v-model:value="formState.phone"
            placeholder="请输入"
            class="formWidth"
            allowClear
          />
        </a-form-item>
      </template>

      <template #form_4>
        <a-form-item name="expiredTime" label="失效时间">
          <a-range-picker
            v-model:value="formState.expiredTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
      </template>

      <template #form_5>
        <a-form-item name="loginTime" label="最近登录时间">
          <a-range-picker
            v-model:value="formState.loginTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
      </template>
    </searchForm>
  </a-form>
  <a-table
    bordered
    row-key="id"
    height="50vh"
    :scroll="{
      y: '60vh'
    }"
    :data-source="data"
    :columns="columns"
    :pagination="{
      pageSize: query.pageSize,
      current: query.pageNum,
      total: total,
      showTotal: (total: number) => `共${total}条数据`,
      showSizeChanger: true,
      showQuickJumper: true,
      onChange: onPageChanged
    }"
  >
  </a-table>
  <TeamMemberTable  v-model:visible="teamMemberVisible" :teamId="curTeamId" :teamName="curTeamName"/>
  <TeamManageDialog
    :title="isAddNew ? '创建团队' : '团队配置'"
    :confirm-loading="confirmLoading"
    v-model:visible="dialogVisible"
    :form="dialogForm"
    :is-phone-readonly="isAddNew ? false : true"
    @handleOk="handleOk"
  />
  

  <a-modal v-model:visible="statusVisible" title="提醒" @ok="handleReject">
    您要{{ statusForm.usedStatus === 0 ? '禁用' : '启用' }}{{ statusForm.phone }}({{
      statusForm.entName
    }})的团队吗？
  </a-modal>
</template>

<script setup lang="ts">
import { message as msgHelper } from 'ant-design-vue'
import { ref, onMounted, reactive, h } from 'vue'
import type { TeamManageColumn, IParam, AuditVO } from '@/api/type'
import {
  apiTeamManageList,
  type TeamManageListParams,
  type TeamForm,
  apiTeamManageUpdate,
  apiUpdateTeamStatus,
  apiCreateTeam
} from '@/api/manage'
import TeamManageDialog from '@/components/TeamManageDialog.vue'
import { getFutureDate } from '@/utils'

const data = ref<Array<AuditVO>>([])
const query = ref<IParam>({
  pageNum: 1,
  pageSize: 20
})
const total = ref<number>(0)

function onPageChanged(page: number, pageSize: number) {
  query.value.pageNum = page
  query.value.pageSize = pageSize
  getList()
}

const getList = async () => {
  try {
    const { loginTime, expiredTime, ...rest } = formState
    const listParam: TeamManageListParams = {
      ...rest,
      ...query.value,
      loginTimeBegin: loginTime?.[0] || '',
      loginTimeEnd: loginTime?.[1] || '',
      expiredTimeBegin: expiredTime?.[0] || '',
      expiredTimeEnd: expiredTime?.[1] || ''
    }
    const res = await apiTeamManageList(listParam)
    console.log(res)
    data.value.splice(0)
    if (!res.data?.entity.rows) return
    const respData = res.data.entity
    data.value.push(...respData.rows)
    total.value = respData.total
  } catch (e) {
    console.log(e)
  }
}
onMounted(() => {
  getList()
})

const tableHeight = ref<number>()
// 重置表单
const formExpertRef = ref()
const resetForm = () => {
  formExpertRef.value.resetFields()
  searchTable()
}
//表格是否可滚动高度
function getTableHeight(height: number) {
  tableHeight.value = height
}
//查询
async function searchTable(isSearchBtn?: Boolean) {
  console.warn(formState, 'formState')
  query.value.pageNum = 1
  getList()
}
const stateOptions = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待审核'
  },
  {
    value: 1,
    label: '已通过'
  },
  {
    value: 2,
    label: '已拒绝'
  }
]

const formState = reactive({
  teamName: '',
  phone: '',
  entName: '',
  expiredTime: [],
  loginTime: []
})

const dialogVisible = ref(false)
const confirmLoading = ref(false)
const dialogForm = ref<TeamForm>({
  phone: '',
  teamName: '',
  entName: '',
  peopleLimit: 10,
  expiredTime: getFutureDate(),
  authorityStatus: 0,
  formulaAuthority: 0,
  id: ''
})
const resetDialogForm = () => {
  dialogForm.value = {
    phone: '',
    teamName: '',
    entName: '',
    peopleLimit: 10,
    expiredTime: getFutureDate(),
    authorityStatus: 0,
    formulaAuthority: 0,
    id: ''
  }
}
const isAddNew = ref(false)
const handleOk = async (form: TeamForm) => {
  confirmLoading.value = true
  try {
    let res
    if (isAddNew.value) {
      res = await apiCreateTeam(form)
    } else {
      res = await apiTeamManageUpdate(form)
    }
    const { data } = res
    console.warn(data,'data');
    
    if (data.code === '200') {
      msgHelper.info(data.message)
      resetDialogForm()
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.log(error)
  } finally {
    confirmLoading.value = false
  }
}

const statusVisible = ref(false)
const statusForm = ref({
  phone: '',
  entName: '',
  teamId: '',
  usedStatus: 0
})

const handleReject = async () => {
  if (!statusForm.value.teamId) return
  const { data } = await apiUpdateTeamStatus({
    teamId: statusForm.value.teamId,
    usedStatus: statusForm.value.usedStatus
  })
  msgHelper.info(data.message)
  statusForm.value = {
    phone: '',
    entName: '',
    teamId: '',
    usedStatus: 0
  }
  statusVisible.value = false
  getList()
}

const teamMemberVisible = ref(false)
const curTeamId = ref('')
const curTeamName = ref('')
const columns = ref<Array<TeamManageColumn>>([
  {
    title: '团队名称',
    dataIndex: 'teamName',
    width: 200
  },
  {
    title: '所属企业',
    dataIndex: 'entName',
    width: 200
  },
  {
    title: '所有者姓名',
    dataIndex: 'customerName',
    width: 200
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 200
  },

  {
    title: '人数上限',
    dataIndex: 'peopleLimit',
    width: 200
  },
  {
    title: '最近登录时间',
    dataIndex: 'lastedLoginTime',
    width: 200
  },
  {
    title: '失效时间',
    dataIndex: 'expiredTime',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
    customRender: ({ record }) => {
      // const record: AuditVO = opt.record as AuditVO
      // if(record.isSuperManager) return <Space />
      return h('span', {}, [
        h(
          'a',
          {
            style: {
              'margin-right': '10px'
            },
            onClick: () => {
              curTeamId.value = record.id || ''
              curTeamName.value = record.teamName || ''
              teamMemberVisible.value = true
            }
          },
          '团队列表'
        ),
        h(
          'a',
          {
            style: {
              'margin-right': '10px'
            },
            onClick: () => {
              console.warn('opt', record)
              const {
                id = '',
                phone = '',
                entName = '',
                peopleLimit = 0,
                expiredTime = '',
                authorityStatus = 0,
                teamName = '',
                formulaAuthority = 0,
              } = record
              dialogForm.value.id = id
              dialogForm.value.teamName = teamName
              dialogForm.value.phone = phone
              dialogForm.value.entName = entName
              dialogForm.value.peopleLimit = peopleLimit
              dialogForm.value.expiredTime = expiredTime
              dialogForm.value.authorityStatus = authorityStatus
              dialogForm.value.formulaAuthority = formulaAuthority
              isAddNew.value = false
              dialogVisible.value = true
            }
          },
          '团队配置'
        ),
        h(
          'a',
          {
            onClick: () => {
              console.warn('opt', record)
              statusForm.value.teamId = record.id || ''
              statusForm.value.phone = record.phone || ''
              statusForm.value.entName = record.entName || ''
              statusForm.value.usedStatus = record.usedStatus === 1 ? 0 : 1
              statusVisible.value = true
            }
          },
          `${record.usedStatus === 1 ? '禁用' : '启用'}`
        )
      ])
    }
  }
])

const addMethods = () => {
  isAddNew.value = true
  resetDialogForm()
  dialogVisible.value = true
}
</script>

<style scoped></style>
